package com.shengyijie.activity.commen;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
 
import com.shengyijie.activity.MainActivity;
import com.shengyijie.activity.R;       
import com.shengyijie.adapter.view.AlertBox; 
import com.shengyijie.adapter.view.AlertBox.OnCanceledListener;
import com.shengyijie.adapter.viewadapter.ItemListAdapter;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.http.HttpConnectApi;   
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.Listobject.AdvertPicList;
import com.shengyijie.model.object.Listobject.ProPictureList;
import com.shengyijie.model.object.Listobject.ProjectList;
import com.shengyijie.model.object.baseobject.Item;    

import android.app.Activity;   
import android.content.Intent; 
import android.os.AsyncTask;
import android.os.Bundle; 
import android.os.Handler;
import android.os.Looper;
import android.os.Message; 
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class ItemListActivity extends Activity implements OnClickListener{
   
	private ListView itemListView;
	private ItemListAdapter listAdapter;
	private TextView tv_no;
	private View preView=null; 
	public Task task;  
	private HttpConnectApi httpConnect;
	
	
	 
	 private ImageButton tabHome;
	 private ImageButton tabCategory;
	 private ImageButton tabRecommended;
	 private ImageButton tabUser;
	 private ImageButton tabMore;
	
	public ArrayList<Item> itemList=new ArrayList<Item>(); ;
	
    public void onCreate(Bundle savedInstanceState){
         super.onCreate(savedInstanceState);
         requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
         setContentView(R.layout.itemlist);
         getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,      // 注意顺序
                 R.layout.title);
         initView();
          
         getIndustryList();
    }
//    @Override  
//         public boolean onTouchEvent(MotionEvent event)
//    {  
//    	return true;
//    }
//    public boolean onKeyDown (int keyCode, KeyEvent event){ 
//    	 
//    	return true; 
//    } 
//    public boolean onKeyUp (int keyCode,KeyEvent event){ 
//    	 
//    	return true; 
//    	} 
    public void initView(){
    	
    	
    	TextView title=(TextView) this.findViewById(R.id.title);
		title.setText(ContextApplication.itemName); 
		
		Button back=(Button) this.findViewById(R.id.back);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		
    	itemListView=(ListView) this.findViewById(R.id.categorylist);  
    	itemListView.setOnItemClickListener(itemClickListener);
    	 
    	 
//    	itemListView.setOnTouchListener(new OnTouchListener(){
//
//			@Override
//			public boolean onTouch(View view, MotionEvent event) {
//				    if(event.getAction()==MotionEvent.ACTION_DOWN){  
//				    	  TextView s=(TextView) view.findViewById(R.id.name);
//				    	  Toast.makeText(ItemListActivity.this, s.getText().toString(), Toast.LENGTH_SHORT).show();			               
//				    	 
//				    }  
//	                if(event.getAction()==MotionEvent.ACTION_UP){  
//	                
//	                }  
//				return false;
//			}});
    	tv_no=(TextView) this.findViewById(R.id.no);
    	tv_no.setVisibility(View.INVISIBLE); 
    	
    	tabHome=(ImageButton) this.findViewById(R.id.home);
    	tabCategory=(ImageButton) this.findViewById(R.id.category);
    	tabRecommended=(ImageButton) this.findViewById(R.id.recommended);
    	tabUser=(ImageButton) this.findViewById(R.id.user);
    	tabMore=(ImageButton) this.findViewById(R.id.more);
		try{
		    switch(ContextApplication.prePage){
		       case ContextApplication.PAGE_HOME:
		    	   tabHome.setSelected(true);
			       break;
		       case ContextApplication.PAGE_CATEGORY:
		    	   tabCategory.setSelected(true);
			       break;
		       case ContextApplication.PAGE_RECOMMENDED:
		    	   tabRecommended.setSelected(true);
			       break;
		       case ContextApplication.PAGE_USER:
		    	   tabUser.setSelected(true);
			       break;
		       case ContextApplication.PAGE_MORE:
		    	   tabMore.setSelected(true);
			       break;
		     }
		 }catch(Exception e){}
		
		 tabHome.setOnClickListener(this);
		 tabCategory.setOnClickListener(this);
		 tabRecommended.setOnClickListener(this);
		 tabUser.setOnClickListener(this);
		 tabMore.setOnClickListener(this);
		 
		 
    }
    
     
    
    public OnItemClickListener itemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			try{
				 preView=view;  
//				 changeListViewApperence(true,view);
	    		 Item content=(Item)parent.getItemAtPosition(position);
	    		 ContextApplication.itemName=content.getName();
	    		 ContextApplication.project=projectList.getItem(position);
//	    		 pro_id=content.getID();
//		    	 task=new Task();  
//    		     task.execute(TASK_LOAD_PIC); 
    		     changeToItemActivity();
				 
			}catch(Exception e){}
			 
		}
    };
    
//    public void changeListViewApperence(boolean change,View view){
//		  try{
//			if(change){  
//		            TextView title=(TextView) view.findViewById(R.id.name);
//		            title.setTextColor(0xffffffff); 
//			}else{ 
//           	        TextView title=(TextView) preView.findViewById(R.id.name);
//		             title.setTextColor(0xff8D2124); 
//			}
//		  }catch(Exception e){}
//		}
//    private static boolean isFirstStart=true;
//    protected void onResume() {
//	      super.onResume();
//	      try{
//	    	  if(!isFirstStart){ 
//			      changeListViewApperence(false,preView);
//	    	  }
//	    	  isFirstStart=false; 
//	      }catch(Exception e){}
//	 }

	@Override
	public void onClick(View v) { 
		Bundle bd = new Bundle();
        bd.putString("state", "exit");	
        Intent it = new Intent();
        it.putExtras(bd);
		switch(v.getId()){
		     case R.id.home:
			    try{
				   if(ContextApplication.prePage!=ContextApplication.PAGE_HOME){
					   MainActivity.tabhost.setCurrentTab(0);
					   setResult(RESULT_OK, it); 
					   this.finish();
				   }
			    }catch(Exception e){}
			    break;
		     case R.id.category:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_CATEGORY){
						   MainActivity.tabhost.setCurrentTab(1);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
		     case R.id.recommended:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_RECOMMENDED){
						   MainActivity.tabhost.setCurrentTab(2);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
		     case R.id.user:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_USER){
						   MainActivity.tabhost.setCurrentTab(3);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
		     case R.id.more:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_MORE){
						   MainActivity.tabhost.setCurrentTab(4);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
				    
		     case R.id.back:
				    try{
					  this.finish();
				    }catch(Exception e){}
				    break;
		}
	}
	
	 public void changeToItemActivity(){
		 Intent intent=new Intent();
		 intent.setClass(this, ItemActivity.class);
		 this.startActivityForResult(intent,1);
	}
	
	 int pro_id; 
	 ProPictureList proPictureList;
	    public String doGetProPicList(){
	     	String result="pp_fail";
	        httpConnect=HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.getProjectPic(pro_id);
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    AdvertPicList advertPicList =jsonParser.getAderts(response);
	           	   // ContextApplication.project.setAdverPicList(jsonParser.getAdert(response));
	           	     
	           	    if(advertPicList!=null){
	           	    	ContextApplication.project.setAdverPicList(advertPicList);
	           	    	if(advertPicList.getCount()>0)
	           	    	    result="pp_ok";
	           	    	else if(advertPicList.getCount()==0)
	           	    		result="pp_0";
	           	    } 
				}
	            return result;
	        }catch (Exception e) {} 
			return result;
	   }
	  
//	 public String doGetProjectDetail(){
//	     	String result="pr_fail";
//	        httpConnect=HttpConnectApi.getInstance();
//	        try { 
//	            HttpResponse response=httpConnect.getProjectDetail(pro_id);
//	            if (response.getStatusLine().getStatusCode() == 200)
//				{ 
//	           	    JsonParser jsonParser=JsonParser.getInstance();
//	           	    ContextApplication.project=jsonParser.getProgectDetail(response);
//	           	    if(ContextApplication.project!=null){ 
//	           	    	 result="pr_ok"; 
//	           	    } 
//				}
//	            return result;
//	        }catch (Exception e) {} 
//			return result;
//	 }
	 
	 public void getIndustryList(){
		 itemListView.postDelayed(new Runnable() {  
             public void run() {   
            	 mypDialog=new AlertBox(ItemListActivity.this,ItemListActivity.this,findViewById(R.id.itemlist)); 
            	 mypDialog.setCompletedListener(new OnCanceledListener(){ 
					@Override
					public void onCanceled() { 
						if(task.getStatus()==AsyncTask.Status.RUNNING){
				    		 task.cancel(true); 
						  }
					}});
            	 task=new Task();   
        	     task.execute(TASK_LOAD_ITEM_LIST); 
             }  
         },1);
	 }
	 
	 public void getIndustryListAdapter(){  
		 Item content=null;
		 for(int i=0;i<projectList.getCount();i++){
			content= new Item(); 
			content.setID(projectList.getItem(i).getID()); 
			content.setImageUrl(projectList.getItem(i).getPro_pic_show());  
			content.setName(projectList.getItem(i).getPro_name()); 
			content.setDes(projectList.getItem(i).getPro_define());
			itemList.add(content);
		 }  
		 listAdapter = new ItemListAdapter(this, itemList, itemListView);   
	}
	 public void getIndustryListAdapterFromLocal(){  
		 Item content=null;
		 for(int i=0;i<projectList.getCount();i++){
			content= new Item(); 
			content.setID(projectList.getItem(i).getID()); 
			content.setImageUrl(projectList.getItem(i).getPro_pic_show());  
			content.setName(projectList.getItem(i).getPro_name()); 
			content.setDes(projectList.getItem(i).getPro_define());
			itemList.add(content);
		 }  
		 listAdapter = new ItemListAdapter(this, itemList, itemListView);   
	}
	 boolean isFirst=true;
	 ProjectList projectList;
	 public String doGetFindIndustry(){
	     	String result="in_fail";
	        httpConnect=HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.getFindIndustry(ContextApplication.industry_id,"0,50");
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    projectList=jsonParser.getAttentionProgect(response);
	           	    if(projectList!=null){
	           	    	if(projectList.getCount()>0){
	           	    		getIndustryListAdapter(); 
	           	    		result="in_ok";
	           	    	} 
	           	    	else if(projectList.getCount()==0)
	           	    		result="in_0";
	           	    } 
				}
	            return result;
	        }catch (Exception e) {} 
			return result;
	   }
	 
	 
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		   if(requestCode==1){
				if (resultCode != RESULT_OK) {
					return;
				}
			   try{
			       String state = data.getStringExtra("state");
			       if(state.equals("exit")){
			    	   Bundle bd = new Bundle();
			           bd.putString("state", "exit");	
			           Intent it = new Intent();
			           it.putExtras(bd);
			           setResult(RESULT_OK, it); 
			    	   this.finish();
			       }
			   }
			   catch(Exception e){}
		   }
	 }
	 
     private AlertBox mypDialog;
      
	 private final static int ALERT_LOADING=1;
	 private final static int RESULT_LOAD_ITEMLIST_OK=2;
	 private final static int RESULT_LOAD_ITEMLIST_0=3; 
	 private final static int RESULT_LOAD_ITEMLIST_FAIL=4;
	 
	 private final static int RESULT_LOAD_ITEMDETAIL_OK=5;
	 private final static int RESULT_LOAD_ITEMDETAIL_FAIL=6;
	 
	 
	  
	 private final static String TASK_LOAD_PIC="loadpic";   
	 private final static String TASK_LOAD_ITEM="loaditem";   
	 private final static String TASK_LOAD_ITEM_LIST="loaditemlist";   
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING: 
					    mypDialog.show();
					    break;  
				   case RESULT_LOAD_ITEMLIST_FAIL:
					   try{
					      mypDialog.dismiss();
					      if(isFirst){
					    	  
					      }
					      Toast.makeText(ItemListActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					      itemListView.setAdapter(null);
			              tv_no.setVisibility(View.VISIBLE);
					    }catch(Exception e){}
					     break;
				    case RESULT_LOAD_ITEMLIST_0:
					     mypDialog.dismiss(); 
					     Toast.makeText(ItemListActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break; 
                    case RESULT_LOAD_ITEMLIST_OK:
                    	try{
	                    	 mypDialog.dismiss(); 
	                    	 itemListView.setAdapter(listAdapter); 
                    	 }catch(Exception e){}
					     break; 
                    case RESULT_LOAD_ITEMDETAIL_OK:
                   	     mypDialog.dismiss(); 
                   	     changeToItemActivity();
					     break; 
                    case RESULT_LOAD_ITEMDETAIL_FAIL:
					     mypDialog.dismiss(); 
					     Toast.makeText(ItemListActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break; 
					     
                     
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {
 
		@Override
		protected String doInBackground(String... params) {
//			if(params[0].equals(TASK_LOAD_ITEM)){
//				return doGetProjectDetail();
//			}
			if(params[0].equals(TASK_LOAD_PIC)){
				return doGetProPicList();
			}else if(params[0].equals(TASK_LOAD_ITEM_LIST)){
				return doGetFindIndustry();
			}else
				return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result); 
			if(result.equals("pr_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("pr_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			}else if(result.equals("pp_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			}else if(result.equals("pp_0")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			}else if(result.equals("pp_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			}
			else if(result.equals("in_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("in_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_OK;
				handler.sendMessage(msg);
			}else if(result.equals("in_0")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_0;
				handler.sendMessage(msg);
			}   
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
		    Message msg = Message.obtain();
		    msg.what = ALERT_LOADING;
			handler.sendMessage(msg); 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
    
}